package cn.bdqn.mallmgr.interceptor;

import cn.bdqn.mallmgr.tools.RedisTool;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author
 * @create 2022-07-13 16:46
 */
public class RecInterceptor implements HandlerInterceptor {

    /**
     * 构造方法，获取bean
     *
     * @param redisTool
     * @return
     */
    public RecInterceptor(RedisTool redisTool) {
        this.redisTool = redisTool;
    }

    private final RedisTool redisTool;

    /**
     * 目标方法执行前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        //拦截规则
        if (token != null && redisTool.exists(token)) {
            //放行
            return true;
        } else {
            //未登录，返回登陆页
            request.setAttribute("msg", "您没有权限进行此操作，请先登陆！");
            request.getRequestDispatcher("/index.html").forward(request, response);
            return false;
        }
    }

    /**
     * 目标方法执行后
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    /**
     * 页面渲染后
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
